<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Validate;
use think\Db;
use app\admin\controller\Zfb;

class Partner extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 申请运营中心/空间/合伙人
     * @ApiMethod (POST)
     * @path api/partner/applyOperate
     */
    public function applyOperate()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        $data = [
            'type' => $params["type"], //申请角色 1=中心,2=空间,3=合伙人
            'realname'=>$params["realname"], //联系人姓名
            'tel'=>$params["tel"], //电话
        ];
        $role = [
            'type' => 'require',
            'realname' => 'require|max:5',
            'tel' => 'require|regex:/^1\d{10}$/',
        ];
        $msg = [
            'type.require' => '申请类型不能为空',
            'realname.require'=>'联系人姓名不能为空',
            'realname.max'=>'联系人姓名最多5个字',
            'tel.require'=>'电话不能为空',
            'tel.regex'=>'手机号码格式错误',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        $apply_data = [];
        $apply_data["user_id"] = $user_id;
        $apply_data["store_id"] = $user->store_id;
        $apply_data["type"] = $params["type"];
        $apply_data["realname"] = $params["realname"];
        $apply_data["tel"] = $params["tel"];
        $apply_data["addtime"] = time();
        if(isset($params["store_name"])){
            $apply_data["store_name"] = $params["store_name"];
        }else{
            $apply_data["store_name"] = "";
        }
        if(isset($params["zizhi"])){
            $apply_data["zizhi"] = parse_url($params["zizhi"])["path"];
        }else{
            $apply_data["zizhi"] = "";
        }
        if(isset($params["zz_num"])){
            $apply_data["zz_num"] = $params["zz_num"];
        }else{
            $apply_data["zz_num"] = "";
        }
        $info = Db::name("apply")->where(["user_id"=>$user_id,"type"=>$params["type"],"user_del"=>'0'])->where('status','in',[1,2])->find();
        if($info){
            $this->error("请勿重复提交申请");
        }
        $today = strtotime(date('Y-m-d'));
        $todayEnd = $today+86400;
        $info1 = Db::name("apply")->where(["user_id"=>$user_id,"type"=>$params["type"],'status'=>3,"user_del"=>'0'])->where("addtime >= $today and addtime < $todayEnd")->find();
        if($info1){
            $this->error("一天只能提交一次");
        }
        $res = Db::name("apply")->insert($apply_data);
        if($res){
            $this->success("申请成功");
        }else{
            $this->error("申请失败");
        }
    }

    /**
     * 申请记录
     * @ApiMethod (Get)
     * @path api/partner/applyLog
     */
    public function applyLog()
    {
        $user_id = $this->auth->id;
        $log = db('apply')->field('id,status,type,addtime,remark')->where(['user_id'=>$user_id,'user_del'=>'0'])->select();
        foreach ($log AS $key => $value) {
            if ($value['type'] == 1) {
                $log[$key]['apply_type_name'] = '申请运营中心';
            } elseif ($value['type'] == 2) {
                $log[$key]['apply_type_name'] = '申请空间';
            } else {
                $log[$key]['apply_type_name'] = '申请空间合伙人';
            }
            $log[$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }
        $this->success("申请成功",[
            'list'=>$log
        ]);
    }

    /**
     * 申请记录详情
     * @ApiMethod (Get)
     * @path api/partner/applyDetail
     */
    public function applyDetail()
    {
        $user_id = $this->auth->id;
        $id = $this->request->param('id');
        $log = db('apply')->field('id,store_name,realname,tel,status,type,addtime,remark,zz_num,zizhi')->where(['user_id'=>$user_id,'id'=>$id,'user_del'=>'0'])->find();
        if (empty($log)) {
            $this->error("记录不存在");
        }
        $log['addtime'] = date('Y-m-d H:i:s',$log['addtime']);
        $log = addWebSiteUrl($log,['zizhi']);
        $this->success("操作成功",[
            'detail'=>$log
        ]);
    }

    /**
     * 申请页面数据回显
     * @ApiMethod (Get)
     * @path api/partner/apply
     */
    public function apply()
    {
        $user_id = $this->auth->id;

        //1=中心,2=空间,3=合伙人
        $type = $this->request->param('type');
        $apply = db('apply')->field('id,store_name,realname,tel,status,type,addtime,remark,zz_num,zizhi')->where(['user_id'=>$user_id,'user_del'=>'0'])->where('type',$type)->order('addtime DESC')->find();
        if (empty($apply)) {
            $this->success("操作成功",[
                'detail'=>[]
            ]);
        }
        $apply['addtime'] = date('Y-m-d H:i:s',$apply['addtime']);
        $apply = addWebSiteUrl($apply,['zizhi']);
        $this->success("操作成功",[
            'detail'=>$apply
        ]);
    }





    /**
     * 合伙人缴费
     * @ApiMethod (POST)
     * @path api/partner/partnerPay
     */
    public function partnerPay()
    {
        $user_id = $this->auth->id;
        $storeId = $this->auth->store_id;
        $id = $this->request->param('id');//申请记录ID
        $userInfo = db('user')->where('id',$user_id)->find();
        $firstPrice = db('config')->where(['name'=>'partner_price_first','group'=>'basic'])->value('value');
        /*****生成缴费记录******/
        $ordernum = generateOrderNumber();
        db("card_pay")->insert([
            'type'=>3,
            'store_id'=>$storeId,
            'user_id'=>$user_id,
            'price'=>$firstPrice,
            'pay_type'=>1,
            'ordernum'=>$ordernum,
            'is_first'=>1,
            'ispay'=>0,
            'addtime'=>time(),
            'user_del'=>0
        ]);

        /********回调start********/
        Db::startTrans();
        try{
            //更新余额
            $user = db('user')->where('id',$user_id)->lock(true)->find();
            db('user')->where('id',$user_id)->setInc('storage_balance',$firstPrice);
            db('user')->where('id',$user_id)->setInc('first_storage_balance',$firstPrice);
            //更新首充状态
            db('user')->where('id',$user_id)->update([
                'is_card_pay'=>1,
                'card_pay_time'=>time()
            ]);
            //增加资金变动明细
            db('card_log')->insert([
                'type'=>3,
                'user_id'=>$user_id,
                'price'=>$firstPrice,
                'new_price'=>$user['storage_balance']+$firstPrice,
                'pay_type'=>1,
                'ordernum'=>generateOrderNumber(),
                'is_first'=>1,
                'ispay'=>1,
                'addtime'=>time(),
                'user_del'=>'0'
            ]);

            db("card_pay")->where('ordernum',$ordernum)->update([
                'ispay'=>1,
            ]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        /********回调end********/

        $this->success("缴费成功");
    }

    //测试合伙人缴费
    public function partnerPay1()
    {
        $user_id = $this->auth->id;
        $storeId = $this->auth->store_id;
        $id = $this->request->param('id');//申请记录ID
        $userInfo = db('user')->where('id',$user_id)->find();
        $firstPrice = db('config')->where(['name'=>'partner_price_first','group'=>'basic'])->value('value');
        /*****生成缴费记录******/
        $ordernum = generateOrderNumber();
        db("card_pay")->insert([
            'type'=>3,
            'store_id'=>$storeId,
            'user_id'=>$user_id,
            'price'=>$firstPrice,
            'pay_type'=>1,
            'ordernum'=>$ordernum,
            'is_first'=>1,
            'ispay'=>0,
            'addtime'=>time(),
            'user_del'=>0
        ]);

        /*****生成拉起在线支付的参数******/
        $Zfb = new Zfb;
        $orderinfo['price']=0.01;
        $orderinfo['order_no']=$ordernum;
        $orderinfo['remark']=$userInfo['username'].'合伙人缴费';
        $orderinfo['store_id']=$storeId;
        $orderinfo['notify']="/fQlTgiAVKu.php/zfb/jiaoFeiNotify";
        // var_dump($orderno);
        $resq = $Zfb->navpay($orderinfo);
        
        
        if($resq['error']==0)
        {
            $json=json_encode($resq['res']); 
            $array = json_decode($json, true);
            
            $qrcode=$this->create_ewm($array['qr_code']);
        
            if($qrcode==1)
            {
                return json([
                    'code'=>201,
                    'msg'=>'请重试'
                ]);
            }
            else
            {
                return json([
                    'code'=>200,
                    'msg'=>'充值成功',
                    'qrcode'=>protocol_name() . '://' . $_SERVER['SERVER_NAME'].$qrcode,
                    'orderno'=>$ordernum
                ]);
            }
            
        }
        else
        {
            return json([
                'code'=>201,
                'msg'=>'请求失败'
            ]);
        }
    }
    //二维码
    public function create_ewm($value){
        //生成二维码
        $matrixPointSize=24;
        vendor('phpqrcode');//引入类库
        $errorCorrectionLevel = 'L';  //容错级别
        // 判断是否有这个文件夹  没有的话就创建一个
        if(!is_dir("uploads/qecode")){
            // 创建文件加
            mkdir("uploads/qecode");
        }
        //设置二维码文件名
        $name=generateOrderNumber();
        $filename = "uploads/qecode/".$name.".png";
        if(file_exists("./".$filename)){
            // return '/'.$filename;
            return 1;
        }
        //生成二维码
        \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize, 2);

        return '/'.$filename;
    }
}
